<template>
  <!-- 页面-应用管理-编辑 -->
  <div style="padding: 10px" class="AppEdit-page">
    <Form :model="modelForm" ref="editForm" :rules="rule" :label-width="126">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="clientId" :label="$t('module.appManage.appCode')">
            <Input
              :placeholder="$t('module.appManage.enterclientId')"
              v-model.trim="modelForm.clientId"
              :disabled="!!appInfo.id"
            />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="appName" :label="$t('module.appManage.appName')">
            <Input
              :placeholder="$t('module.appManage.enterappName')"
              v-model.trim="modelForm.appName"
              :disabled="readOnly"
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <!-- <Col span="12">
          <Form-item prop="userRepository" :label="$t('module.appManage.userCenter')">
            <Select
              :placeholder="$t('module.appManage.warning.selectUserCenter')"
              v-model="modelForm.userRepository"
              class="no-borderColor"
              :disabled="readOnly"
            >
              <Option v-for="itemKey in Object.keys(userRepositorys)" :value="itemKey" :key="itemKey">{{
                userRepositorys[itemKey]
              }}</Option>
            </Select>
          </Form-item>
        </Col>-->
        <Col span="12">
          <Form-item prop="tenantName" :label="$t('module.appManage.tenant')">
            <Input v-model="modelForm.tenantName" disabled />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="domainName" :label="$t('module.appManage.domainName')">
            <Input
              :placeholder="$t('module.appManage.enterdomainName')"
              v-model="modelForm.domainName"
              :maxlength="128"
              :disabled="readOnly"
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item
            prop="accessTokenValidity"
            :label="$t('module.appManage.tokenExpirationTime')"
            class="accessTokenValidity"
          >
            <Input
              :placeholder="$t('module.appManage.enteraccessTokenValidity')"
              v-model="modelForm.accessTokenValidity"
              @on-keyup="checkInputNumber"
              :maxlength="50"
              :disabled="readOnly"
            />
            <span>S</span>
          </Form-item>
        </Col>
        <!-- 状态 -->
        <Col span="12" style="border: none">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1" :disabled="readOnly">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0" :disabled="readOnly">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <!-- 刷新TOKEN周期 -->
        <Col span="12">
          <Form-item
            prop="refreshTokenValidity"
            :label="$t('module.appManage.refreshtokenExpirationTime')"
            class="refreshTokenValidity"
          >
            <Input
              :placeholder="$t('module.appManage.enterrefreshTokenValidity')"
              v-model="modelForm.refreshTokenValidity"
              @on-keyup="checkInputNumber"
              :maxlength="50"
              :disabled="readOnly"
            />
            <span>S</span>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="18">
          <Form-item prop="clientSecretPlaintext" :label="$t('module.appManage.clientSecretPlaintext')">
            <Input v-model="modelForm.clientSecretPlaintext" disabled placeholder :maxlength="50" />
          </Form-item>
        </Col>
        <Col span="6">
          <Form-item :labelWidth="0">
            <RPButton
              optType="reset"
              @click.native="getClientSecret"
              :text="$t('module.appManage.generateclientSecret')"
              style="borderradius: 0; width: 100%"
              :disabled="readOnly"
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="webServerRedirectUri" :label="$t('module.appManage.webServerRedirectUri')">
            <Input
              :placeholder="$t('module.appManage.enterwebServerRedirectUri')"
              v-model="modelForm.webServerRedirectUri"
              :maxlength="300"
              :disabled="readOnly"
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="authorizedGrantTypes" :label="$t('module.appManage.loginMode')">
            <Input v-model="modelForm.authorizedGrantTypes" placeholder disabled />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="langs" :label="$t('module.appManage.langs')">
            <Select v-model="supportLangs" multiple :transfer="true" :disabled="readOnly">
              <Option v-for="item in languageList" :title="item.langDesc" :value="item.langCode" :key="item.langCode">
                {{ item.langDesc }}
              </Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="loginTypes" :label="$t('module.appManage.loginType')">
            <Select
              :placeholder="$t('module.appManage.enterloginType')"
              :transfer="true"
              v-model="checkedLogintype"
              class="no-borderColor"
              multiple
              :disabled="readOnly"
            >
              <Option v-for="itemKey in Object.keys(loginTypes)" :value="itemKey" :key="itemKey">
                {{ loginTypes[itemKey] }}
              </Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="24">
          <Form-item prop="isOpen" :label="$t('module.appManage.mainDataSwitch')">
            <i-switch v-model="modelForm.isOpen" true-color="#ff6f4b">
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import { getUUID } from "@/tools/util.js";
import locales from "./locales.js";
import {
  searchAppList,
  getAppById,
  saveOrUpdateApp,
  getMainDataStatus,
  openMainDataStatus,
  closeMainDataStatus
} from "@/api/applicationApi.js";
import valueSetAPI from "@/api/valueSetAPI.js";
import { getUserCenterList } from "@/api/userCenterApi.js";
import tenantAPI from "@/api/tenantApi.js";
import { codeReg, CoreModuleName } from "@/const.js";

export default {
  name: "appedite",
  mixins: [locales],
  props: {
    appInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    tenantName: {
      type: String,
      default() {
        return "";
      }
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const validateClientId = (rule, value, callback) => {
      if (value === "" || value === null || value === undefined) {
        callback(new Error(this.$t("module.appManage.enterclientId")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      }
      callback();
    };
    const tokenValidity = (rule, value, callback) => {
      if (value == "" || value == null) {
        callback(new Error(this.$t("module.appManage.enteraccessTokenValidity")));
      }
      if (parseFloat(value).toString() == "NaN") {
        callback(new Error(this.$t("module.appManage.warning.tokenValidityNumber")));
      }
      callback();
    };
    const refreshToken = (rule, value, callback) => {
      if (value == "" || value == null) {
        callback(new Error(this.$t("module.appManage.enterrefreshTokenValidity")));
      }
      if (parseFloat(value).toString() == "NaN") {
        callback(new Error(this.$t("module.appManage.warning.requireNumber")));
      }
      callback();
    };
    const domainValidate = (rule, value, callback) => {
      const domain = /^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$/
      const ipv6Reg = /^(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(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-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))\](?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/i
      const ipv4Reg = /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/
      console.log(domain.test(value) , ipv4Reg.test(value) , ipv6Reg.test(value));
      if (!domain.test(value) && !ipv4Reg.test(value) && !ipv6Reg.test(value)) {
        callback(new Error(this.$t("module.appManage.enterRightdomainName")));
      }
      callback();
    };
    const { userInfo } = $store.state[CoreModuleName];
    return {
      currTenantCode: userInfo.tenantCode || "", //租户编码
      actions: [],
      remoteLoading: false,
      isReadyOnly: false,
      checkedscope: [],
      checkedauthorizedGrantTypes: [],
      checkedLogintype: [],
      userRepositorys: {},
      // scopes: {},
      loginmodes: {},
      loginTypes: {},
      languageList: [],
      supportLangs: ["zh-CN"],
      isOpen: false,
      modelForm: {
        clientId: null,
        appName: null,
        userRepository: "default",
        domainName: null,
        clientSecretPlaintext: null,
        scope: null,
        webServerRedirectUri: null,
        accessTokenValidity: "6000",
        refreshTokenValidity: null,
        authorizedGrantTypes: "password,refresh_token,client_credentials,authorization_code",
        loginTypes: null,
        langs: null,
        tenantName: null,
        enabled: 1,
        isOpen: false
      },
      rule: {
        clientId: [
          {
            required: true,
            validator: validateClientId,
            trigger: "blur"
          },
          {
            type: 'string',
            max: 30,
            message: this.$t("common.warning.lengMaxFormat", ['30'])
          }, 
          {
            type: 'string',
            pattern: /^[a-zA-Z0-9|_|\-|\.]+$/,
            message: this.$t("common.warning.codeFormat")
          }
        ],
        appName: [
          {
            required: true,
            message: this.$t("module.appManage.enterappName"),
            trigger: "blur"
          },
          {
            type: 'string',
            max: 64,
            message: this.$t("common.warning.lengMaxFormat", ['64'])
          },
          {
            type: 'string',
            pattern: /[\u4E00-\u9FA5]|[A-Z]|[a-z]|[0-9]/,
            message: this.$t("common.warning.nameFormat")
          }
        ],
        // userRepository: [
        //   {
        //     required: true,
        //     message: this.$t("module.appManage.enteruserRepository"),
        //     trigger: "blur"
        //   }
        // ],
        domainName: [
          {
            required: true,
            message: this.$t("module.appManage.enterdomainName"),
            trigger: "blur"
          },
          { validator: domainValidate, trigger: "blur" }
        ],
        clientSecretPlaintext: [
          {
            required: true,
            message: this.$t("module.appManage.enterclientSecret"),
            trigger: "blur"
          }
        ],
        accessTokenValidity: [
          {
            required: true,
            validator: tokenValidity,
            trigger: "blur"
          }
        ],
        refreshTokenValidity: [
          {
            required: true,
            validator: refreshToken,
            trigger: "blur"
          }
        ],
        tenantName: [{ required: true, trigger: "blur" }],
        isOpen: [{ required: true }]
      }
    };
  },
  created() {
    if (this.readOnly) {
      this.$emit("SetTitle", this.$t("common.detail"));
    } else if (this.appInfo.id) {
      this.$emit("SetTitle", this.$t("module.appManage.editApp"));
      // TODO 主数据同步
      this.getMainDataStatus();
    } else {
      this.$emit("SetTitle", this.$t("module.appManage.createApp"));
    }
    // 调整宽度
    this.$emit("SetPageWidth", 774);
    if (!this.readOnly) {
      this.actions.push({
        text: this.$t("common.save"),
        theme: "primary",
        handle: () => {
          this.save();
        },
        loading: false
      });
    }
    this.actions.push({
      text: this.$t("common.close"),
      theme: "primary",
      handle: () => {
        this.$emit("Close");
      }
    });
    this.$emit("SetPageActions", this.actions);
    this.initData();
  },
  methods: {
    getMainDataStatus() {
      let { tenantCode, clientId: applicationCode } = this.row;
      getMainDataStatus({
        tenantCode,
        applicationCode
      }).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.isOpen = res.data;
          this.modelForm.isOpen = res.data;
        }
      });
    },
    checkInputNumber(e) {
      e.target.value = e.target.value.replace(/\D/g, "");
    },
    getClientSecret() {
      let temp = getUUID().replace(new RegExp("-", "g"), "");
      this.modelForm.clientSecretPlaintext = temp;
    },
    // searchScope() {
    //   this.remoteLoading = true;
    //   searchAppList({ pageNum: 1, pageSize: 200 })
    //     .then(response => {
    //       this.remoteLoading = false;
    //       let dicArrScope = response.data.records;
    //       this.scopes = {};
    //       for (let i = 0; i < dicArrScope.length; i++) {
    //         let dicscope = dicArrScope[i];
    //         this.scopes[dicscope.clientId] = dicscope.appName;
    //       }
    //     })
    //     .catch(error => {});
    // },
    async initData() {
      // if()
      // this.searchScope();
      //获取产品类型
      const result = await Promise.all([valueSetAPI.getValueSetByCode("LOGIN_MODE"), getUserCenterList()]);
      //   结构赋值
      const [dicArrLogin, { data: userTemp }] = result;
      this.loginmodes = {};
      for (let i = 0; i < dicArrLogin.length; i++) {
        let diclogin = dicArrLogin[i];
        this.loginmodes[diclogin.vsiKey] = diclogin.vsiValue;
      }
      this.userRepositorys = {};
      for (let i = 0; i < userTemp.length; i++) {
        let temp = userTemp[i];
        this.userRepositorys[temp.userCenterId] = temp.userCenterName;
      }

      if (!!this.appInfo.id) {
        this.isReadyOnly = true;
        this.getDataById();
      }

      // 语言清单
      valueSetAPI.getValueSetByCode("languageList").then(data => {
        for (const lang of data) {
          this.languageList.push({
            langDesc: lang.vsiValue,
            langCode: lang.vsiKey
          });
        }
      });
      //登录类型清单
      valueSetAPI.getValueSetByCode("LOGIN_TYPE").then(loginTypeArr => {
        for (let i = 0; i < loginTypeArr.length; i++) {
          let loginType = loginTypeArr[i];
          this.loginTypes[loginType.vsiKey] = loginType.vsiValue;
        }
        this.loginTypes = Object.assign({}, this.loginTypes);
      });
      //新增时
      if (!this.appInfo.id) {
        this.modelForm.tenantName = this.tenantName;
      }
    },
    getDataById() {
      getAppById(this.appInfo.id)
        .then(response => {
          Object.assign(this.modelForm, response.data);
          this.modelForm.accessTokenValidity = this.modelForm.accessTokenValidity + ""; //处理校验问题
          this.modelForm.refreshTokenValidity = this.modelForm.refreshTokenValidity + ""; //处理校验问题
          const res = response.data;
          // this.modelForm.tenantName = res.tenantCode;
          this.initTenant(res.tenantCode); //获取租户编码对应的租户名称
          if (this.modelForm.scope) {
            this.checkedscope = this.modelForm.scope.split(",");
          }
          if (this.modelForm.langs) {
            this.supportLangs = this.modelForm.langs.split(",");
          }
          if (this.modelForm.loginTypes) {
            this.checkedLogintype = this.modelForm.loginTypes.split(",");
          } else {
            this.checkedLogintype = [];
          }
          // 这里需要一个根据clientId 查应用详情
          // this.getAppByCliented(this.checkedscope);
        })
        .catch(error => {
          this.$message.error({
            content: error.message,
            duration: 3
          });
        });
    },
    // 初始化所属租户,获取租户编码对应的租户名称
    initTenant(tenantCode) {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          if (tenantCode == tenant.tenantCode) {
            this.modelForm.tenantName = tenant.tenantName;
          }
        }
      });
    },
    // getAppByCliented(codes) {
    // getApplicationByCliendId(codes)
    //   .then(response => {
    //     let dicArrScope = response.data;
    //     // this.scopes = {};
    //     // for (let i = 0; i < dicArrScope.length; i++) {
    //     //   let dicscope = dicArrScope[i];
    //     //   this.scopes[dicscope.clientId] = dicscope.appName;
    //     // }
    //   })
    //   .catch(error => {
    //     this.$message.error({
    //       content: error.message,
    //       duration: 3
    //     });
    //   });
    // },
    // QueryLoginTypeData() {
    //   //获取登录类型
    //   return new Promise((resolve, reject) => {
    //     $store
    //       .dispatch("GetValueSetByCode", {
    //         code: "LOGIN_TYPE"
    //       })
    //       .then(response => {
    //         resolve(response);
    //       })
    //       .catch(error => {
    //         this.$message.error({
    //           content: error.message,
    //           duration: 3
    //         });
    //       });
    //   });
    // },
    openOrCloseMainDataStatus() {
      let params = {
        applicationCode: this.modelForm.clientId,
        tenantCode: this.currTenantCode
      };
      if (this.appInfo.id) {
        // 编辑
        if (this.modelForm.isOpen === this.isOpen) {
          return false;
        }
        if (this.modelForm.isOpen) {
          // 开启
          openMainDataStatus(params).then(res => {
            console.log(res, "openMainDataStatus");
            if (res.code !== 200) {
              this.$message.error({
                content: res.message,
                duration: 3
              });
            }
          });
        } else {
          // 关闭
          closeMainDataStatus(params).then(res => {
            console.log(res, "closeMainDataStatus");
            if (res.code !== 200) {
              this.$message.error({
                content: res.message,
                duration: 3
              });
            }
          });
        }
      } else {
        // 新建
        if (this.modelForm.isOpen) {
          // 开启
          openMainDataStatus(params).then(res => {
            console.log(res, "openMainDataStatus");
            if (res.code !== 200) {
              this.$message.error({
                content: res.message,
                duration: 3
              });
            }
          });
        }
      }
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.checkedscope.length > 0) {
            this.modelForm.scope = this.checkedscope.join();
          }
          if (this.supportLangs.length > 0) {
            this.modelForm.langs = this.supportLangs.join(",");
          }
          if (this.checkedLogintype.length > 0) {
            this.modelForm.loginTypes = this.checkedLogintype.join();
          } else {
            this.modelForm.loginTypes = "";
          }

          // this.modelForm.webServerRedirectUri = this.modelForm.domainName; // 否则登录 cas 有问题

          this.modelForm.accessTokenValidity = parseFloat(this.modelForm.accessTokenValidity);
          this.modelForm.refreshTokenValidity = parseFloat(this.modelForm.refreshTokenValidity);
          saveOrUpdateApp(this.modelForm)
            .then(response => {
              this.openOrCloseMainDataStatus(); // 主数据同步
              this.actions[0].loading = false;
              const content = this.appInfo.id
                ? this.$t("module.valueSet.updateSuccess")
                : this.$t("module.valueSet.createSuccess");
              this.$message.success({
                content: content,
                duration: 3
              });
              this.$emit("Close", true);
            })
            .catch(err => {
              this.actions[0].loading = false;
            });
        } else {
          this.$message.error({
            content: this.$t("module.valueSet.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    }
  },
  watch: {}
};
</script>
<style lang="less">
.AppEdit-page {
  .accessTokenValidity,
  .refreshTokenValidity {
    .ivu-input-wrapper {
      width: calc(~"100% - 14px") !important;
    }
  }
}
</style>
